<?php
/**
 * Created by PhpStorm.
 * User: alei
 * Date: 11/5/2017 AD
 * Time: 16:58
 */
namespace App\Models\Mysql;

//use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\BaseDBMethod;

class pre_forum_pollvoter
{
	use BaseDBMethod;
	//数据库连接配置项，见config/database.php
	const DATABASE_CONF = 'lqyw_mysql';
	//pre_ct_ui 首页轮播图所在表
	const TABLE_NAME = 'pre_forum_pollvoter';

	//数据库连接配置项，见config/database.php
	//如果需要用ORM，需要设置此项
//	protected $connection = self::DATABASE_CONF;
	//表名，如果需要用ORM，需要设置此项
//	protected $table = self::TABLE_NAME;

	public static function find_vote($v,$param)
	{
		$r=self::getConnObj()->select(
			"SELECT * FROM pre_forum_pollvoter   WHERE tid=:tid and uid=:uid limit 1",
			[
				'tid' => $v,
				'uid' => $param['uid'],
			]
		);
		if($r)
		{
		    return 1;
        }
        else
        {
            return 0;
        }
	}

    public static function get_count($param)
    {
        return self::getConnObj()->select(
            "SELECT count(*) count FROM  pre_ct_translatedtext   WHERE taskid=:taskid ",
            [
                'taskid' => $param,
            ]
        );
    }

    #查看是否投票
    public static function find($param)
    {
        $r=self::getConnObj()->select(
            "SELECT * FROM pre_forum_pollvoter   WHERE tid=:tid and uid=:uid limit 1",
            [
                'tid' => $param['tid'],
                'uid' => $param['uid'],
            ]
        );
        if($r)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    #插入投票信息
    public static function add($arr)
    {
        $r=db()->insert('pre_forum_pollvoter',$arr);
        if($r[0])
        {
            return $r[0];
        }
        else
        {
            return false;
        }
    }
    #更新投票信息
    public static function modify($param)
    {
        $r=self::getConnObj()->update("UPDATE pre_forum_polloption SET votes=votes+1 WHERE tid={$param['tid']} and polloption='{$param['author']}'");
        if($r)
        {
            return self::getConnObj()->select("SELECT polloptionid FROM pre_forum_polloption WHERE  tid={$param['tid']} and polloption='{$param['author']}'");
        }
        else
        {
            $param['votes']=1;
            unset($param['uid']);
            unset($param['author']);
            return db()->insert('pre_forum_polloption',$param);
        }
    }

    public static function test()
    {
        return db()->query(" SELECT polloptionid FROM pre_forum_polloption WHERE  tid= 210");
    }

    public static function option($param)
    {
        return self::getConnObj()->select("select polloptionid, polloption from pre_forum_polloption where tid={$param['tid']}");
    }

    #验证实名认证
    public static function check($uid)
    {
        return self::getConnObj()->select("select uid from pre_common_member_profile where uid=$uid and  field1='CERTIFIED'");
    }

    #投票流程开始
    public static function voting_process($vote_ids,$tid)
    {
        #$voterweight  = pre_common_member_field_forum.ctvoteweight where uid=当前用户id如果上述查询找不到,$voterweight使用默认权重1
        //根据投票数修正权重，保证每个用户对投票结果的“影响”和他投的票数无关。（类似“送花”）
        $uid = (int)$_SESSION['uid'];
        $username = $_SESSION['user_name'];
        $r = self::getConnObj()->select("select ctvoteweight from pre_common_member_field_forum where uid=$uid");
        $voterweight = empty($r) ? 1 : $r[0]->ctvoteweight;
        $ids = implode(',', $vote_ids);
        $tempc = count($vote_ids);
        $voterweight *= (($tempc > 0) ? (6 / $tempc) : 1);
        $r1 = self::getConnObj()->update("UPDATE pre_forum_polloption
                                    SET 
                                    votes=votes+1,
                                    weightedvotes=weightedvotes+$voterweight, 
                                    voterids=concat(voterids,'".$uid."\t')"." WHERE polloptionid IN ($ids)");
        $t = time();
        #修改主题表时间戳
        $r2 = self::getConnObj()->update("update pre_forum_thread SET lastpost=$t WHERE tid=$tid");

        #修改投票总数控制表
        $r3 = self::getConnObj()->update("UPDATE pre_forum_poll SET voters=voters+1 WHERE tid=$tid");
        #往投票记录表里插入投票记录
        $options = implode("\t", $vote_ids);
        $t = time();
        $r4 = self::getConnObj()->insert("insert into pre_forum_pollvoter(`tid`,`uid`,`username`,`options`,`dateline`)
                                VALUES ($tid,$uid,'{$username}','{$options}',$t)");

        #更新投票积分
        $r5 = self::getConnObj()->select("select ct_tran.tid" .
            " from pre_ct_translatedtext ct_tran, pre_forum_polloption fpo" .
            " where ct_tran.polloptionid=fpo.polloptionid and ct_tran.submitphase=1" .
            " and fpo.polloptionid in($ids)");
        $tran_ids = [];
        foreach ($r5 as $k => $v) {
            $tran_ids[] = $v->tid;
        }
        $t_ids = implode(',', $tran_ids);
        if (!empty($r5)) {
            //更新（被投票的）译文积分
            self::getConnObj()->update("update pre_ct_translatedtext SET ctcredit = ctcredit +$voterweight
            where tid in($t_ids)");

            //更新（被投票的）译文作者积分
            $auth = self::getConnObj()->select("select authorid from pre_forum_thread " .
                " where tid in($t_ids)");
            $auth_ids = [];
            foreach ($auth as $k => $v) {
                $auth_ids[] = $v->authorid;
            }

            $u_ids = implode(',', $auth_ids);
            self::getConnObj()->update("update pre_common_member SET credits= credits +$voterweight
            where uid in($u_ids)");


        }
    }

    static public  function  vote_display($parm)
    {
        //查看用户是投票
        $vote_status = self::getConnObj()->select("select * from pre_forum_pollvoter 
            where tid={$parm['tid']}  and uid={$parm['uid']} ");
        #标题，查看数，回复数
        $obj = self::getConnObj()->select("select `subject`,`replies`,`views` from pre_forum_thread 
            where tid={$parm['tid']} ");
        #投票总人数
        $count= self::getConnObj()->select("select `voters` from pre_forum_poll
            where tid={$parm['tid']} ");
        #加权重票数
        $vote_num=self::getConnObj()->select("select `tid`,`polloption`,`weightedvotes` from pre_forum_polloption
            where tid={$parm['tid']} ");

        $r=!empty($vote_status) ?  1: 0;
        $obj[0]->vote_status=$r;
        $obj[0]->count_man=$count[0]->voters;
        $obj[0]->vote_display=$vote_num;
        return $obj;
    }

    static public  function  getPollInfoByPolltid($tid)
	{
         return self::getConnObj()->select("select * from pre_forum_poll where tid={$tid}");
	}

}